﻿using AduSkin.Controls.Metro;
using HsServerHa.Common.Auth;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using HsServerHa.ViewModel;
using HsServerHa.WinPage;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// VirtuallyIPSetting.xaml 的交互逻辑
    /// </summary>
    public partial class VirtuallyIPSetting : UserControl
    {


        public DbHelperSQLite helper;
        public string adapterName;
        public VirtuallyIPSetting()
        {
            InitializeComponent();
            this.DataContext = new VirtuallyIPSettingViewModel();

            InitData();

        }

        public void InitData()
        {
            if (App.isMaster != null)
            {
                if (!App.isMaster.Value)
                {
                    this.VirtuallyIP.Visibility = Visibility.Hidden;
                    this.Lbl_VirtuallyIP.Visibility = Visibility.Hidden;
                    this.VirtuallyIP.Text = "";
                }
            }
            //查询数据库表
            //var dataSet = DbHelperSQLite.Query("SELECT * FROM \"VirtuallyManage\"");

            //DataTable dt = dataSet.Tables.Count > 0 ? dataSet.Tables[0] : new DataTable();
            //List<VirtuallyManageEntity> list = DataHelpers.ConvertToModel<VirtuallyManageEntity>(dt);
            var list = SQLiteHelper.Table<VirtuallyManageEntity>().ToList();
            if (list.Count > 0)
            {
                adapterName = list[0].NetworkCardName;
                VirtuallyIP.Text = list[0].VirtuallyIP;
                ReferIP.Text = list[0].ReferIP;
            }

            var adapterList = NetWorkHelper.GetNetworkInfo();

            int index = 0;
            int? subIndex = null;
            foreach (var adapter in adapterList)
            {
                string Name = adapter.Name;
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = Name;
                AdapterSelector.Items.Add(cbi);
                if (Name == adapterName)
                {
                    subIndex = index;
                }
                index++;
            }
            if (subIndex != null)
            {
                AdapterSelector.SelectedIndex = subIndex.Value;
            }
        }



        private ManagementObject? GetNetAdapter(string name)
        {
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapter"))
            {
                var ns = mc.GetInstances().Cast<ManagementObject>().Where(x => x["NetEnabled"] != null && (bool)x["NetEnabled"] == true).ToList();
                return ns.Where(x => (string)x["Name"] == name).FirstOrDefault();
            }
        }
        private int SetMacAddress(string adapterName, string newMac)
        {
            ManagementObject? mo = GetNetAdapter(adapterName);
            if (mo == null) return -1;

            uint index = (uint)mo["Index"];
            SetMacAddress(index, newMac);

            try
            {
                mo.InvokeMethod("Disable", null);
                mo.InvokeMethod("Enable", null);
            }
            catch
            {
                return -2;
            }
            return 0;
        }
        private void SetMacAddress(uint index, string newMac)
        {
            //得到 MAC的注册表键
            RegistryKey? macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}").
                OpenSubKey(index.ToString().PadLeft(4, '0'), true);
            if (macRegistry == null) return;

            if (string.IsNullOrEmpty(newMac))
            {
                macRegistry.DeleteValue("NetworkAddress");
            }
            else
            {
                macRegistry.SetValue("NetworkAddress", newMac);
                //macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac);
                //macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("ParamDesc", "Network Address");
            }
        }
        /// <summary>
        /// 原MAC
        /// </summary>
        public string OriginalMAC { get; set; }
        /// <summary>
        /// 设置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AuthorizationVerification.ShowAuthBox();
                return;
            }

            #endregion
            if (AdapterSelector.SelectedValue == null || string.IsNullOrEmpty(AdapterSelector.SelectedValue.ToString()))
            {
                AduMessageBoxs.Show("请选择网卡");
                return;
            }
            if (!NetWorkHelper.IsStaticIP(CurrIP.Text))
            {
                AduMessageBoxs.Show($"请将你的IP（{CurrIP.Text}）固定！");
                return;
            }

            if (!NetWorkHelper.ValidateMask(SubnetMask.Text))
            {
                AduMessageBoxs.Show("子网掩码格式不正确！");
                return;
            }
            if (!string.IsNullOrEmpty(Gateway.Text))
            {
                if (!NetWorkHelper.ValidateIpAddress(Gateway.Text))
                {
                    AduMessageBoxs.Show("网关格式不正确！");
                    return;
                }
            }

            if (!NetWorkHelper.ValidateIpAddress(CurrIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的当前IP");
                return;
            }
            if (App.isMaster.Value)
            {
                if (!NetWorkHelper.ValidateIpAddress(VirtuallyIP.Text))
                {
                    AduMessageBoxs.Show("请输入正确的虚拟IP");
                    return;
                }

                if (NetWorkHelper.IsPingIP(VirtuallyIP.Text))
                {
                    AduMessageBoxs.Show("该虚拟IP已使用，请换一个IP");
                    return;
                }

                if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(CurrIP.Text, VirtuallyIP.Text))
                {
                    AduMessageBoxs.Show("虚拟IP和当前IP不在同一网段！");
                    return;
                }
            }
            if (!NetWorkHelper.ValidateIpAddress(ReferIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的参考IP");
                return;
            }
            else
            {
                if (!NetWorkHelper.IsPingIP(ReferIP.Text))
                {
                    AduMessageBoxs.Show("请输入合法的参考IP");
                    return;
                }
            }



            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定要选择当前网卡{adapterName}？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {

                string[] IPs = new string[2];
                IPs[0] = CurrIP.Text;
                IPs[1] = VirtuallyIP.Text;

                string[] Masks = new string[2];
                Masks[0] = SubnetMask.Text;
                Masks[1] = SubnetMask.Text;

                string[] DNS;
                if (string.IsNullOrEmpty(DNS2.Text))
                {
                    DNS = new[] { DNS1.Text };
                }
                else
                {
                    DNS = new[] { DNS1.Text, DNS2.Text };
                }

                //var isSuccess = SetIPAddress(adapter, IPs, Masks, new string[] { Gateway.Text}, DNS);
                if (true)
                {
                    int NTEContext = 0;
                    int NTEInstance;
                    //var str = $" netsh interface ip set address name={NetWorkHelper.adapterName} source=static address={CurrIP.Text} mask={SubnetMask.Text}  ";

                    //if (!string.IsNullOrEmpty(Gateway.Text))
                    //{
                    //    str += $" gateway={Gateway.Text}";
                    //}

                    //var cmd = str;
                    //NetWorkHelper.HandleCMDCommand(cmd);
                    if (App.isMaster.Value)
                    {
                        //str += $" & netsh interface ipv4 delete address name={NetWorkHelper.adapterName}  addr={VirtuallyIP.Text}  gateway=all";
                        //str += $" &  netsh interface ipv4 add address name={NetWorkHelper.adapterName} addr={VirtuallyIP.Text} mask={SubnetMask.Text}  ";
                        //if (!string.IsNullOrEmpty(Gateway.Text))
                        //{
                        //    str += $" gateway={Gateway.Text}";
                        //}
                        string virtualIP = this.VirtuallyIP.Text; // 虚拟IP地址
                        string subnetMask = this.SubnetMask.Text; // 子网掩码
                        int interfaceIndex = NetWorkHelper.GetInterfaceIndex(NetWorkHelper.adapterName); // 网卡接口索引
                        if (interfaceIndex == -1)
                        {
                            AduMessageBoxs.Show("网卡配置错误，请重新选择！");
                            return;
                        }

                        var result = NetWorkHelper.AddVirtualIPAddress((uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(virtualIP).GetAddressBytes(), 0), (uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(subnetMask).GetAddressBytes(), 0), interfaceIndex, out NTEContext, out NTEInstance);
                        if (result != 0)
                        {
                            AduMessageBoxs.Show("请检查虚拟IP是否合法！");
                            return;
                        }

                    }




                    //先删除，然后新增
                    SQLiteHelper.ExecuteSql("delete from VirtuallyManage");
                    var iSu = SQLiteHelper.ExecuteSql($"insert into VirtuallyManage (CurrIP,SubnetMask,Gateway,DNS1,DNS2,MAC,VirtuallyIP,NetworkCardName,CreateTime,ReferIP,VirtuallyIPKey)  values('{CurrIP.Text}','{SubnetMask.Text}','{Gateway.Text}','{DNS1.Text}','{DNS2.Text}','{MAC.Text}','{VirtuallyIP.Text}','{adapterName}','{DateTime.Now.ToString()}','{ReferIP.Text}','{NTEContext}') ");
                    var isBindSu = 0;

                    //修改绑定表
                    if (App.isMaster.Value)
                    {
                        isBindSu = SQLiteHelper.ExecuteSql($"UPDATE MasterSlaveBind SET MasterIP = '{CurrIP.Text}',   VirtuallyIP = '{VirtuallyIP.Text}' ");
                    }
                    else
                    {
                        isBindSu = SQLiteHelper.ExecuteSql($"UPDATE MasterSlaveBind SET  SlaveIP = '{CurrIP.Text}' ");
                    }

                    if (iSu <= 0 && isBindSu <= 0)
                    {
                        AduMessageBoxs.Show("设置失败");
                        LoggerHelper.SetInfo("设置失败", "IP资源设置");
                        return;
                    }
                    App.GatewayIP = Gateway.Text;
                    App.ReferIP = ReferIP.Text;
                    App.VirtuallyIP = VirtuallyIP.Text;
                    App.CurrIP = CurrIP.Text;


                    if (OriginalMAC != MAC.Text.ToString())
                    {
                        //更改网卡MAC地址，网卡状态为启用时才会生效
                        if (PhysicalAddress.TryParse(MAC.Text, out PhysicalAddress? mac))
                        {
                            int result = SetMacAddress(NetWorkHelper.adapter.Description, MAC.Text);
                            if (result != 0)
                            {
                                //设置失败
                                AduMessageBoxs.Show("设置MAC地址失败,请检查网卡是否为启用状态!");
                                return;
                            }
                        }
                    }


                    //重新获取网卡信息
                    NetWorkHelper.GetNetworkInfo();
                    InitData();
                    AduMessageBoxs.Show("设置成功");
                    LoggerHelper.SetInfo("设置成功", "IP资源设置");
                }
                else
                {
                    AduMessageBoxs.Show("设置失败");
                    LoggerHelper.SetInfo("设置失败", "IP资源设置");
                    return;
                }

                var control = this.Parent as ContentControl;
                Window win = Window.GetWindow(control);
                var title = win?.Title;
                if (title != null)
                {
                    if (title != "HsServerHa")
                    {
                        win.Close();
                    }

                }

                return;
            }

        }



        /// <summary>
        /// 网卡下拉框事件
        /// 朱润来
        /// 2023年10月10日14:01:34
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AdapterSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            string content = AdapterSelector.SelectedValue.ToString();
            NetWorkHelper.adapterName = content.Replace("System.Windows.Controls.ComboBoxItem: ", "");

            if (NetWorkHelper.GetAdapterInfoDataByName(NetWorkHelper.adapterName))
            {
                CurrIP.Text = NetWorkHelper.CurrIPStr;
                SubnetMask.Text = NetWorkHelper.SubnetMaskStr;
                Gateway.Text = NetWorkHelper.GatewayStr;
                DNS1.Text = NetWorkHelper.DNS1Str.Contains("ffff") ? "" : NetWorkHelper.DNS1Str;
                DNS2.Text = NetWorkHelper.DNS2Str.Contains("ffff") ? "" : NetWorkHelper.DNS2Str;
                MAC.Text = NetWorkHelper.MACStr;
                OriginalMAC = NetWorkHelper.MACStr;
                adapterName = NetWorkHelper.adapterName;

            }
        }



        private void btn_Del_Click(object sender, RoutedEventArgs e)
        {
            if (RemoveIPAddress())
            {
                AduMessageBoxs.Show("删除成功");
            }
            else
            {
                AduMessageBoxs.Show("删除失败");
            }
        }

        private bool RemoveIPAddress()
        {

            if (NetWorkHelper.GetAdapterInfoDataByName(NetWorkHelper.adapterName))
            {
                string[] DNS;
                if (string.IsNullOrEmpty(NetWorkHelper.DNS2Str))
                {
                    DNS = new[] { DNS1.Text };
                }
                else
                {
                    DNS = new[] { DNS1.Text, DNS2.Text };
                }


                //var isSuccess= SetIPAddress(adapter, new string[] { CurrIPStr }, new string[] { SubnetMaskStr }, new string[] { GatewayStr }, DNS);
                if (true)
                {
                    if (string.IsNullOrEmpty(NetWorkHelper.VirtuallyIPStr))
                    {
                        AduMessageBoxs.Show("不存在虚拟IP");
                        return false;
                    }
                    var cmd = $" netsh interface ipv4 delete address name={NetWorkHelper.adapterName}  addr={NetWorkHelper.VirtuallyIPStr} ";
                    NetWorkHelper.HandleCMDCommand(cmd);

                    NetWorkHelper.GetNetworkInfo();
                }
                return true;
            }
            else
            {
                return false;
            }



        }
    }
}
